import { Component, OnInit } from '@angular/core';
import { differenceInCalendarDays, differenceInMinutes, format } from 'date-fns';
import { FormGroup, FormBuilder, FormControl } from '@angular/forms';
import { ApiService } from '@core/api.service';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { _HttpClient } from '@delon/theme';
import { DatePipe } from '@angular/common';
import { LocalStorage } from '@core/local.storage';
import { StatusFollowService } from '@core/statusFollow.service';
import { environment } from '../../../../environments/environment';

@Component({
  selector: 'app-jhwcqk',
  templateUrl: './jhwcqk.component.html',
  styleUrls: ['./jhwcqk.component.less']
})
export class JhwcqkComponent implements OnInit {
  constructor(
    private apiService: ApiService,
    private activatedRoute: ActivatedRoute,
    private fb: FormBuilder,
    private http: _HttpClient,
    private datePipe: DatePipe,
    public ls: LocalStorage,
    private statusFollowService: StatusFollowService
  ) { }

  validateForm: FormGroup;
  data: any;
  today: Date = new Date();
  expandDataCache: { id?: string } = {};
  loadingData = true;
  queryUrl: string;
  lockHeadScroll = { y: window.innerHeight - 350 + 'px' };
  lockHeadScroll2 = { x: '4000px', y: 500 + 'px' };
  controlNames: any = {
    begindate: 'begindate',
    enddate: 'enddate',
    cj: 'cj',
    gq: 'gq',
  };
  linkConfig = {
    jhwcqk: '/workorderpreparation/view',
    pgdwcqk: '/workorderpreparation/view',
    sgjhwcqk: '/workorderpreparation/view',
    sgpgdwcqk: '/workorderpreparation_sg/view',
  };
  cjList: any;
  gqList: any;
  userInfo = JSON.parse(this.ls.get('loginInfo'));
  pageType: any;
  routerLink: any;

  itemData: any = {};
  examData: any = {};
  examStatus: any = {};
  pageTotal = '';
  selectedValue = '20';
  pageValue = '20';
  pageIndex = 1;
  rowPage = 1;
  rowTotal = 0;
  expandTitle = '';
  expandVisible = false;
  tabsIndex = 0;

  ngOnInit(): void {
    this.initControls();
    this.getCj();
    this.activatedRoute.data.subscribe((params: Params) => {
      this.pageType = params.type;
      switch (params.type) {
        // case 'jhwcqk': // 计划完成情况
        //   this.queryUrl = environment.apiBase + '/csmis/daywork/ymtwadayworksgrwx/getrwxstatistics.jwt';
        //   break;
        case 'pgdwcqk': // 派工单完成情况
          this.queryUrl = environment.apiBase + '/csmis/daywork/ymtwadayworksgrwx/getrwxpgdstatistics.jwt';
          this.routerLink = this.linkConfig[params.type];
          break;
        // case 'sgjhwcqk': // 计划完成情况
        //   this.queryUrl = environment.apiBase + '/csmis/peihesg/phtconstructsgxt/getrsgstatistics.jwt';
        //   break;
        case 'sgpgdwcqk': // 派工单完成情况
          this.queryUrl = environment.apiBase + '/csmis/peihesg/phtconstructsgxt/getrsgpgdstatistics.jwt';
          break;
        default:
          break;
      }
      // this.tabsBack();
      this.getStatistics();
      this.validateForm.patchValue({
        [this.controlNames.begindate]: this.datePipe.transform(new Date(), 'yyyy-MM-dd'),
        [this.controlNames.enddate]: this.datePipe.transform(new Date(), 'yyyy-MM-dd'),
      });
    });
  }

  // tabsBack() {
  //   switch (this.pageType) {
  //     case 'jhwcqk':
  //     case 'sgjhwcqk':
  //       this.tabsIndex = 1;
  //       break;
  //     case 'pgdwcqk':
  //     case 'sgpgdwcqk':
  //       this.tabsIndex = 0;
  //       break;
  //   }
  // }

  tabsChange(e) {
    switch (this.pageType) {
      // case 'jhwcqk':
      case 'pgdwcqk':
        switch (e.index) {
          case 0:
            this.queryUrl = environment.apiBase + '/csmis/daywork/ymtwadayworksgrwx/getrwxstatistics.jwt';
            break;
          case 1:
            this.queryUrl = environment.apiBase + '/csmis/daywork/ymtwadayworksgrwx/getrwxpgdstatistics.jwt';
            this.routerLink = this.linkConfig.pgdwcqk;
            break;
        }
        break;
      // case 'sgjhwcqk':
      case 'sgpgdwcqk':
        switch (e.index) {
          case 0:
            this.queryUrl = environment.apiBase + '/csmis/peihesg/phtconstructsgxt/getrsgstatistics.jwt';
            break;
          case 1:
            this.queryUrl = environment.apiBase + '/csmis/peihesg/phtconstructsgxt/getrsgpgdstatistics.jwt';
            break;
        }
        break;
    }
    this.getStatistics();
    this.validateForm.patchValue({
      [this.controlNames.begindate]: this.datePipe.transform(new Date(), 'yyyy-MM-dd'),
      [this.controlNames.enddate]: this.datePipe.transform(new Date(), 'yyyy-MM-dd'),
    });
  }

  collapse(array, data, $event: boolean): void {
    if (!$event) {
      if (data.children) {
        data.children.forEach(d => {
          const target = array.find(a => a.id == d.id);
          if (target) {
            target.expand = false;
            this.collapse(array, target, false);
          }
        });
      } else {
        return;
      }
    }
  }

  private visitNode(node, hashMap: object, array): void {
    if (!hashMap[node.id]) {
      hashMap[node.id] = true;
      array.push(node);
    }
  }

  private convertTreeToList(root: object) {
    const stack = [];
    const array = [];
    const hashMap = {};
    stack.push({ ...root, level: 0, expand: false });
    while (stack.length) {
      const node = stack.pop();
      this.visitNode(node, hashMap, array);
      if (node.children) {
        for (let i = node.children.length - 1; i >= 0; i--) {
          stack.push({ ...node.children[i], level: node.level + 1, expand: false, parent: node });
        }
      }
    }
    return array;
  }

  setQueryDate(type) {
    let start, end;
    switch (type) {
      case 'day':
        const today = this.datePipe.transform(new Date(), 'yyyy-MM-dd');
        start = today;
        end = today;
        break;
      case 'week':
        const beginDate_w = new Date();
        const weekday = beginDate_w.getDay();
        beginDate_w.setDate(beginDate_w.getDate() - weekday + 1);
        const endDate_w = new Date();
        endDate_w.setDate(beginDate_w.getDate() + 6);
        start = this.datePipe.transform(beginDate_w, 'yyyy-MM-dd');
        end = this.datePipe.transform(endDate_w, 'yyyy-MM-dd');
        break;
      case 'month':
        const beginDate_m = new Date();
        beginDate_m.setDate(1);
        const endDate_m = new Date();
        endDate_m.setMonth(endDate_m.getMonth() + 1);
        endDate_m.setDate(0);
        start = this.datePipe.transform(beginDate_m, 'yyyy-MM-dd');
        end = this.datePipe.transform(endDate_m, 'yyyy-MM-dd');
        break;
    }
    this.validateForm.patchValue({
      [this.controlNames.begindate]: start,
      [this.controlNames.enddate]: end,
    });
  }

  clickExpand(finish, item) {
    const begindate = this.datePipe.transform(this.validateForm.value.begindate, 'yyyy-MM-dd');
    const enddate = this.datePipe.transform(this.validateForm.value.enddate, 'yyyy-MM-dd');
    let orgid = '';

    if (this.validateForm.value.gq) {
      orgid = this.validateForm.value.gq;
    } else if (item.level == 1) {
      orgid = item.id;
    }

    this.itemData = {
      'finish': finish,
      'orgid': orgid,
      'cjorgid': item.level == 0 ? item.id : '',
      'begindate': begindate,
      'enddate': enddate
    };
    this.expandVisible = true;
    this.examData.jhwcqk = [];
    this.examData.pgdwcqk = [];
    this.examData.sgjhwcqk = [];
    this.examData.sgpgdwcqk = [];
    this.examStatus.jhwcqk = false;
    this.examStatus.pgdwcqk = false;
    this.examStatus.sgjhwcqk = false;
    this.examStatus.sgpgdwcqk = false;
    this.rowPage = 1;
    this.readyload(this.rowPage, this.pageValue);
  }

  readyload(rowPage, pageValue) {
    this.itemData.begindate = this.datePipe.transform(this.itemData.begindate, 'yyyy-MM-dd');
    this.itemData.enddate = this.datePipe.transform(this.itemData.enddate, 'yyyy-MM-dd');
    switch (this.pageType) {
      case 'jhwcqk': // examconstructionplan
        this.examStatus.jhwcqk = true;
        this.expandTitle = '计划完成情况';
        const params = '?page=' + rowPage + '&rows=' + pageValue + '&orgid=' + this.itemData.orgid + '&cjorgid=' + this.itemData.cjorgid + '&finish=' + this.itemData.finish + '&types=&status=&begindate=' + this.itemData.begindate + '&enddate=' + this.itemData.enddate;
        this.apiService.finddayworksgrwx(params).subscribe((res: any) => {
          if (res.type === 'success') {
            this.examData.jhwcqk = res.data.pageList;
            this.pageTotal = res.data.pageCount;
            this.rowTotal = res.data.pageCount;
          }
        });
        break;
      case 'pgdwcqk': // workorderpreparation
        this.examStatus.pgdwcqk = true;
        this.expandTitle = '派工单完成情况';
        this.apiService.finddayworksgrwxPGD(rowPage, pageValue, this.datePipe.transform(this.itemData.begindate, 'yyyy-MM-dd'), this.datePipe.transform(this.itemData.enddate, 'yyyy-MM-dd'), '', '', this.itemData.cjorgid, this.itemData.orgid, this.itemData.finish, '').subscribe((res: any) => {
          if (res.type === 'success') {
            this.examData.pgdwcqk = res.data.pageList;
            this.pageTotal = res.data.pageCount;
            this.rowTotal = res.data.pageCount;
          }
        });

        break;
      case 'sgjhwcqk': // workorderpreparation_sg
        this.examStatus.sgjhwcqk = true;
        this.expandTitle = '计划完成情况';
        this.apiService.finddayworksgrwx_sg('', '', this.itemData.orgid, this.itemData.cjorgid, this.itemData.finish, this.datePipe.transform(this.itemData.begindate, 'yyyy-MM-dd'), this.datePipe.transform(this.itemData.enddate, 'yyyy-MM-dd'), rowPage, pageValue).subscribe((res: any) => {
          if (res.type === 'success') {
            this.examData.sgjhwcqk = res.data.pageList;
            this.pageTotal = res.data.pageCount;
            this.rowTotal = res.data.pageCount;
          }
        });
        break;
      case 'sgpgdwcqk': // examconstructionplan_sg
        this.examStatus.sgpgdwcqk = true;
        this.expandTitle = '派工单完成情况';
        this.apiService.finddayworksgrwxPGD_sg(rowPage, pageValue, this.datePipe.transform(this.itemData.begindate, 'yyyy-MM-dd'), this.datePipe.transform(this.itemData.enddate, 'yyyy-MM-dd'), '', '', this.itemData.cjorgid, this.itemData.orgid, this.itemData.finish, '').subscribe((res: any) => {
          if (res.type === 'success') {
            this.examData.sgpgdwcqk = res.data.pageList;
            this.pageTotal = res.data.pageCount;
            this.rowTotal = res.data.pageCount;
          }
        });
        break;
    }
  }

  expandOk() {
    this.expandVisible = false;
  }

  rowChangeTable(ev) {
    this.rowPage = ev;
    this.readyload(this.rowPage, this.pageValue);
  }

  statusFollow(data) {
    return this.statusFollowService.init('1', data);
  }

  getStatistics() {
    const vfv = this.validateForm.value;

    let begindate = '';
    if (vfv.begindate instanceof Date) {
      begindate = this.datePipe.transform(vfv.begindate, 'yyyy-MM-dd');
    } else {
      begindate = vfv.begindate || '';
    }
    let enddate = '';
    if (vfv.enddate instanceof Date) {
      enddate = this.datePipe.transform(vfv.enddate, 'yyyy-MM-dd');
    } else {
      enddate = vfv.enddate || '';
    }

    const orgid = vfv.gq || '';
    const cjorgid = vfv.cj || '';

    const param = {
      begindate,
      enddate,
      cjorgid,
      orgid,
    };

    const url = this.queryUrl;

    if (!url) {
      return;
    }
    this.http.get(url, param).subscribe((res: any) => {
      this.data = res.data;
      this.loadingData = false;
      this.data.forEach(item => {
        this.expandDataCache[item.id] = this.convertTreeToList(item);
      });
    });
  }


  disabledDate = (current: Date): boolean => {
    // Can not select days before today and today
    return differenceInCalendarDays(current, this.today) > 0 ||
      differenceInCalendarDays(current, new Date(2016, 0)) < 0;
  }

  private initControls() {
    this.validateForm = this.fb.group({});
    const values = Object.values(this.controlNames);
    values.forEach((el: any) => {
      this.validateForm.addControl(el, new FormControl());
    });
  }

  getCj() {
    this.apiService.getAllChejian('1').subscribe(res => {
      let _data;
      if (typeof res == 'string') {
        _data = JSON.parse(res);
      } else {
        _data = res;
      }
      let delIndex;
      for (let i = 0; i < _data.length; i++) {
        const el = _data[i];
        if (!el.opValue) {
          delIndex = i;
        }
      }
      _data.splice(delIndex, 1);
      this.cjList = _data;
      if (_data.length === 1) {
        this.validateForm.patchValue({ [this.controlNames.cj]: _data[0].opValue });
      }
    });
  }

  cjChange(cjId) {
    this.getgq(cjId);
  }

  getgq(cjId?) {
    if (this.userInfo.N_LEVEL == 10 || !cjId) {// gq
      cjId = this.userInfo.VC_PAR$ORG$ID;
    }
    this.apiService.getgongquByCjId(cjId || '').subscribe(res => {
      let _data;
      if (typeof res == 'string') {
        _data = JSON.parse(res);
      } else {
        _data = res;
      }
      let delIndex;
      for (let i = 0; i < _data.length; i++) {
        const el = _data[i];
        if (!el.opValue) {
          delIndex = i;
        }
      }
      _data.splice(delIndex, 1);
      this.gqList = _data;
    });
  }

  calcMinutes = (sT: string, eT: string): number => {
    const todayStr = format(this.today, 'YYYY-MM-DD') + ' ';
    const gapMinutes = differenceInMinutes(todayStr + eT, todayStr + sT);
    return gapMinutes < 0 ? gapMinutes + 24 * 60 : gapMinutes;
  }
}
